$(document).ready(function() {
    // 检查登录状态
    const userId = localStorage.getItem('userId');
    const role = localStorage.getItem('role');
    
    if (!userId || role !== '1') {
        window.location.href = '../index.html';
        return;
    }

    // 加载商品列表
    loadProducts();

    // 退出登录
    $('#logout').click(function(e) {
        e.preventDefault();
        localStorage.removeItem('userId');
        localStorage.removeItem('role');
        window.location.href = '../index.html';
    });

    // 添加商品按钮点击事件
    $('#addProductBtn').click(function() {
        openModal();
    });

    // 商品表单提交事件
    $('#productForm').submit(function(e) {
        e.preventDefault();
        saveProduct();
    });

    // 确保商品编辑弹窗初始状态为隐藏
    $('#productModal').hide();

    // 添加确认弹窗的HTML到页面
    $('body').append(`
        <div id="confirmModal" class="modal" style="display: none;">
            <div class="modal-content">
                <h3>确认删除</h3>
                <p>确定要删除该商品吗？此操作不可恢复。</p>
                <div class="modal-actions">
                    <button onclick="confirmDelete()" class="primary-btn">确认删除</button>
                    <button onclick="closeConfirmModal()" class="secondary-btn">取消</button>
                </div>
            </div>
        </div>
    `);

    // 修改样式定义
    $('<style>')
        .text(`
            .modal {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1001;
            }
            .modal-content {
                background-color: white;
                padding: 20px;
                border-radius: 8px;
                min-width: 300px;
                text-align: center;
                position: relative;
            }
            .modal-actions {
                margin-top: 20px;
                display: flex;
                justify-content: center;
                gap: 10px;
            }
            .modal-actions button {
                min-width: 80px;
            }
            .message {
                position: fixed;
                left: 50%;
                transform: translateX(-50%);
                padding: 15px 30px;
                border-radius: 4px;
                z-index: 1002;
                color: white;
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                text-align: center;
                min-width: 200px;
                top: 20%;
            }
            .message.success {
                background-color: #4CAF50;
            }
            .message.error {
                background-color: #f44336;
            }
        `)
        .appendTo('head');
});

function loadProducts() {
    const sellerId = localStorage.getItem('userId');
    
    $.ajax({
        url: `/api/commodity/seller/${sellerId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                const products = response.data.sort((a, b) => {
                    if (a.status !== b.status) {
                        return b.status - a.status;
                    }
                    return a.commodityId - b.commodityId;
                });

                const container = $('#productList');
                container.empty();
                
                products.forEach(product => {
                    // 如果库存为0但状态为上架，自动更新为下架状态
                    if (product.stock === 0 && product.status === 1) {
                        updateProductStatus(product.commodityId, 1, false);
                        product.status = 0;
                    }
                    
                    container.append(`
                        <div class="product-card">
                            <div class="product-info">
                                <h3 title="${product.commodityName}">${product.commodityName}</h3>
                                <div>¥${product.price.toFixed(2)}</div>
                                <div>库存：${product.stock}</div>
                            </div>
                            <div class="product-actions">
                                <button onclick="editProduct(${product.commodityId})" class="primary-btn">修改商品</button>
                                <button onclick="toggleProductStatus(${product.commodityId}, ${product.status})" 
                                        class="secondary-btn">
                                    ${product.status === 1 ? '下架商品' : '上架商品'}
                                </button>
                                ${Number(product.status) === 0 ? 
                                    `<button onclick="deleteProduct(${product.commodityId})" class="delete-btn">删除商品</button>` 
                                    : ''}
                            </div>
                        </div>
                    `);
                });
            } else {
                showMessage(response.message, 'error');
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading products:', error);
            showMessage('加载商品列表失败', 'error');
        }
    });
}

function openModal(product = null, autoEnable = false) {
    // 重置表单状态
    $('#productForm')[0].reset();
    $('#commodityId').val('');
    
    $('#modalTitle').text(product ? '编辑商品' : '添加商品');
    // 添加一个隐藏字段用于标记是否需要自动上架
    if (!$('#autoEnable').length) {
        $('<input>').attr({
            type: 'hidden',
            id: 'autoEnable',
            value: 'false'
        }).appendTo('#productForm');
    }
    $('#autoEnable').val(autoEnable);
    
    if (product) {
        $('#commodityId').val(product.commodityId);
        $('#commodityName').val(product.commodityName);
        $('#price').val(product.price);
        $('#stock').val(product.stock);
    }
    $('#productModal').show();
}

function closeModal() {
    $('#productModal').hide();
}

function saveProduct() {
    const sellerId = localStorage.getItem('userId');
    const commodityId = $('#commodityId').val();
    const stock = parseInt($('#stock').val());
    const isAutoEnable = $('#autoEnable').val() === 'true'; // 用于标记是否需要自动上架
    
    const productData = {
        commodityName: $('#commodityName').val(),
        price: parseFloat($('#price').val()),
        stock: stock,
        sellerId: parseInt(sellerId),
        status: commodityId ? undefined : 0 // 新商品默认下架，修改商品保持原状态
    };

    if (commodityId) {
        productData.commodityId = parseInt(commodityId);
    }

    $.ajax({
        url: '/api/commodity/' + (commodityId ? 'update' : 'add'),
        type: commodityId ? 'PUT' : 'POST',
        contentType: 'application/json',
        data: JSON.stringify(productData),
        success: function(response) {
            if (response.code === 200) {
                let message = commodityId ? '商品修改成功' : '商品添加成功';
                
                // 如果需要自动上架且库存大于0
                if (isAutoEnable && stock > 0) {
                    // 执行上架操作
                    $.ajax({
                        url: '/api/commodity/update/status',
                        type: 'PUT',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            commodityId: commodityId,
                            status: 1
                        }),
                        success: function(statusResponse) {
                            if (statusResponse.code === 200) {
                                message += '，商品已上架';
                            }
                            showMessage(message);
                            closeModal();
                            loadProducts();
                        }
                    });
                } else if (isAutoEnable && stock === 0) {
                    // 如果尝试自动上架但库存为0
                    showMessage('库存为0，不能上架商品', 'error');
                    closeModal();
                    loadProducts();
                } else {
                    if (stock === 0) {
                        // 如果是修改操作且库存改为0，需要下架商品
                        if (commodityId) {
                            $.ajax({
                                url: '/api/commodity/update/status',
                                type: 'PUT',
                                contentType: 'application/json',
                                data: JSON.stringify({
                                    commodityId: commodityId,
                                    status: 0
                                }),
                                success: function(statusResponse) {
                                    if (statusResponse.code === 200) {
                                        showMessage('商品已下架');
                                        closeModal();
                                        loadProducts();
                                    }
                                }
                            });
                        } else {
                            showMessage(message);
                            closeModal();
                            loadProducts();
                        }
                    } else {
                        showMessage(message);
                        closeModal();
                        loadProducts();
                    }
                }
            } else {
                showMessage(response.message, 'error');
            }
        }
    });
}

function editProduct(commodityId) {
    $.ajax({
        url: `/api/commodity/${commodityId}`,
        type: 'GET',
        success: function(response) {
            if (response.code === 200) {
                openModal(response.data);
            }
        }
    });
}

function toggleProductStatus(commodityId, currentStatus) {
    // 如果是要上架商品，先检查库存
    if (currentStatus === 0) {
        // 获取商品信息
        $.ajax({
            url: `/api/commodity/${commodityId}`,
            type: 'GET',
            success: function(response) {
                if (response.code === 200) {
                    if (response.data.stock === 0) {
                        showMessage('库存为0，不能上架商品', 'error');
                        // 打开编辑弹窗，并标记需要自动上架
                        openModal(response.data, true);
                        return;
                    }
                    // 库存充足，继续上架操作
                    updateProductStatus(commodityId, currentStatus);
                }
            }
        });
    } else {
        // 下架操作直接执行
        updateProductStatus(commodityId, currentStatus);
    }
}

// 修改状态更新函数，添加是否显示消息的参数
function updateProductStatus(commodityId, currentStatus, showMsg = true) {
    const newStatus = currentStatus === 1 ? 0 : 1;
    
    $.ajax({
        url: '/api/commodity/update/status',
        type: 'PUT',
        contentType: 'application/json',
        data: JSON.stringify({
            commodityId: commodityId,
            status: newStatus
        }),
        success: function(response) {
            if (response.code === 200) {
                if (showMsg) {
                    showMessage(newStatus === 1 ? '商品已上架' : '商品已下架');
                }
                loadProducts();
            } else {
                if (showMsg) {
                    showMessage(response.message, 'error');
                }
            }
        },
        error: function(xhr, status, error) {
            console.error('Error updating status:', error);
            if (showMsg) {
                showMessage('更新商品状态失败', 'error');
            }
        }
    });
}

let pendingDeleteId = null;

function deleteProduct(commodityId) {
    pendingDeleteId = commodityId;
    $('#confirmModal').show();
}

function closeConfirmModal() {
    $('#confirmModal').hide();
    pendingDeleteId = null;
}

function confirmDelete() {
    if (pendingDeleteId === null) return;
    
    const commodityId = pendingDeleteId;
    closeConfirmModal();
    
    $.ajax({
        url: `/api/commodity/${commodityId}`,
        type: 'DELETE',
        success: function(response) {
            if (response.code === 200) {
                showMessage('商品删除成功');
                loadProducts();
            } else {
                showMessage(response.message, 'error');
            }
        }
    });
}

function showMessage(message, type = 'success') {
    const messageDiv = $('<div>')
        .addClass('message')
        .addClass(type)
        .text(message)
        .css('opacity', 0);

    // 如果当前有显示的弹窗，将消息放在弹窗上方
    const activeModal = $('.modal:visible');
    if (activeModal.length > 0) {
        const modalTop = activeModal.find('.modal-content').offset().top;
        messageDiv.css('top', Math.max(modalTop - 80, 20) + 'px');
    }

    $('body').append(messageDiv);
    messageDiv.animate({ opacity: 1 }, 300);

    setTimeout(() => {
        messageDiv.animate({ opacity: 0 }, 300, function() {
            $(this).remove();
        });
    }, 1500);
}